/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.sun.lwuit.Command;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BoxLayout;
import core.IMAPMIDlet;
import core.PositionManager;
import core.RuntimeData;
import core.ScreenEngine;
import datamodel.Message;
import network.Connection;
import network.PacketBuilder;
import view.additional.CellItem;
import view.additional.MenuList;
import view.commands.BackCommand;

/**
 *
 * @author Kvest
 */
public class PositionActionsForm extends BasicForm implements MenuList.MenuListSelection
{
    private static final int SHOW_INFO_TIMEOUT = 10000;
    private static final int OK_COMMAND_ID = 1;
    
    private static final int TO_POSITION_ITEM_ID = 0;
    private static final int FROM_POSITION_ITEM_ID = 1;
    private static final int POSITION_INFO_ITEM_ID = 2;
    private static final int POSITION_INFO_FULL_ITEM_ID = 3;
    private static final int STEP_BACK_ITEM_ID = 4;
    
    private MenuList items;
    private CellItem positionInfo;
    private CellItem positionInfoFull;
    private CellItem stepBack;
    
    private PositionsForm positionsForm = new PositionsForm();
    
    private PositionManager positionManager;
    
    public PositionActionsForm()
    {
        super("position");
        
        positionManager = IMAPMIDlet.getMidlet().getPositionManager();
        
        init();
    }
    
    private void init()
    {
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        setScrollable(false);
        
        items = new MenuList();
        items.addItem(new CellItem(TO_POSITION_ITEM_ID, "to_position"));
        items.addItem(new CellItem(FROM_POSITION_ITEM_ID, "from_position"));
        positionInfo = new CellItem(POSITION_INFO_ITEM_ID, "pos_info");
        items.addItem(positionInfo);
        positionInfoFull = new CellItem(POSITION_INFO_FULL_ITEM_ID, "pos_info_full");
        items.addItem(positionInfoFull);
        stepBack = new CellItem(STEP_BACK_ITEM_ID, "step_back");
        items.addItem(stepBack);
        items.setSelectionListener(this);
        addComponent(items);
        
        //Команды
        addCommand(new BackCommand());
        
        Command ok = new Command("ok", OK_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
                itemSelected(items.getSelectedId()); 
                
                evt.consume();
            }
        };
        addCommand(ok);
    }
    
    public void show()
    {
        //Устанавливаем активные\неактивные пункты
        setItemsState();
        
        super.show();
    }
    
    private void setItemsState()
    {
        positionInfo.setEnabled(state == CONNECTED_STATE);
        positionInfoFull.setEnabled(state == CONNECTED_STATE);
        stepBack.setEnabled(state == CONNECTED_STATE);
    }
    
    public void itemSelected(int id)
    {
        switch(id)
        {
            case TO_POSITION_ITEM_ID: showPositions(); break;
            case FROM_POSITION_ITEM_ID : unregisterPosition(); break;
            case POSITION_INFO_ITEM_ID : requestPositionsInfo(); break;
            case POSITION_INFO_FULL_ITEM_ID : requestFullPositionsInfo(); break;
            case STEP_BACK_ITEM_ID : doStepBack(); break;
        }
    }
    
    private void unregisterPosition()
    {
        //Формируем и отправляем запрос
        RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
        byte[] body = PacketBuilder.createUnRegisterOnTaxiParking(runtimeData.getPeopleID());
        byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
        Connection.getConnection().send(data);
        
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
    }
    
    private void doStepBack()
    {
        //Формируем и отправляем запрос
        RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
        byte[] body = PacketBuilder.createMoveBackInQueue(1, runtimeData.getPeopleID());
        byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
        Connection.getConnection().send(data);
        
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
    }
    
    private void showPositions()
    {
        //Проверяем наличие стоянок и коллбэком ставим обновление форму стоянок
        positionManager.checkForPositionUpdates(new Runnable() 
        {
            public void run() 
            {
                //Обновляем форму отображения стоянок
                if (positionsForm != null)
                {
                    positionsForm.setContent();
                    positionsForm.repaint();
                }
            }
        }, 
        new Runnable() 
        {
            public void run() 
            {
                //Просто принудительно перерисовываем форму - все остальное сделает сама форма
                if (positionsForm != null && positionsForm.isVisible())
                {
                    positionsForm.repaint();
                }
            }
        });
        
        //Отображаем форму со стоянками
        showPositionsForm();
    }
    
    private void showPositionsForm()
    {
        if (positionsForm == null)
        {
            positionsForm = new PositionsForm();
        }
        
        //Отображаем
        ScreenEngine.getEngine().push(positionsForm);
    }
    
    private void requestPositionsInfo()
    {
        //Запускаем обновление статистики
        positionManager.checkForPositionUpdates(null, 
        new Runnable() 
        {
            public void run() 
            {
                //Отображаем сообщение
                showPositionsInfo();
            }
        });
        
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
    }
    
    private void requestFullPositionsInfo()
    {
        //Запускаем обновление статистики
        positionManager.checkForPositionUpdates(null, 
        new Runnable() 
        {
            public void run() 
            {
                //Отображаем сообщение
                showFullPositionsInfo();
            }
        });
        
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
    }
    
    private void showPositionsInfo()
    {
        Message message = new Message(positionManager.getPositionsInfo()); 
        message.setTimeout(SHOW_INFO_TIMEOUT);
        IMAPMIDlet.getMidlet().getMessageManager().newMessage(message);
    }
    
    private void showFullPositionsInfo()
    {
        Message message = new Message(positionManager.getFullPositionsInfo()); 
        message.setTimeout(SHOW_INFO_TIMEOUT);
        IMAPMIDlet.getMidlet().getMessageManager().newMessage(message);
    }
}
